import com.google.gson.GsonBuilder
import java.io.*
import java.lang.Exception
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import meta.entity.MetaTree

fun String.replaceLast(regex: String, replacement: String): String {
    return this.replaceFirst("(?s)$regex(?!.*?$regex)".toRegex(), replacement)
}

object UtilFuncs {

    var count: Int = 0

    fun saveMetaFile(saveObj: Any, savePath: String){
        try {
            PrintWriter(FileWriter(savePath)).use {
                val gson = GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create()
                val rootStr = gson.toJson(saveObj)
                it.write(rootStr)
            }
        }catch (e: Exception){
            e.printStackTrace()
        }
    }

    fun saveMetaFile2(saveObj: String, savePath: String){
        try {
            PrintWriter(FileWriter(savePath)).use {
                it.write(saveObj)
            }
        }catch (e: Exception){
            e.printStackTrace()
        }
    }

    fun saveMetaFile3(saveObj: MetaTree, savePath: String){
        try {
            PrintWriter(FileWriter(savePath)).use {
                it.write(Json.encodeToString(saveObj))
            }
        }catch (e: Exception){
            e.printStackTrace()
        }
    }

    fun unique(length:Int, size:Int = 1): MutableList<String> {
        val charset = ('a'..'z') + ('A'..'Z') + ('0'..'9')
        val result = mutableListOf<String>()
        for (i in 0 until size){
            result.add(List(length) { charset.random() }.joinToString(""))
        }
        return result
    }

    fun counterFormat(length: Int = 2, prefex:String = "", refresh:Boolean = false): String {
        if(refresh) count = 0
        else count++
        return prefex + String.format("%0${length-1}d", count)
    }

    fun readFile(filePath:String):String {
        val file = File(filePath)
        val reader = BufferedReader(FileReader(file))
        var result = ""
        reader.lines().forEach { result += it }
        return result
    }

}